<template>
  <div class="post-form-container">
    <el-form 
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="post-form"
    >
      <!-- 帖子类型 -->
<!--      <el-form-item label="帖子类型" prop="type">-->
<!--        <el-select v-model="formData.type" placeholder="请选择帖子类型" >-->
<!--          <el-option label="寻人启事" value="finding" />-->
<!--          <el-option label="警方悬赏" value="police" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <!-- 基本信息 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述相关情况"
        />
      </el-form-item>

      <!-- 失踪人员信息 -->
      <el-form-item label="姓名" prop="personName">
        <el-input v-model="formData.personName" placeholder="请输入失踪人员姓名" />
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="formData.age" :min="1" :max="120" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender" >
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="失踪日期" prop="missingDate">
        <el-date-picker
          v-model="formData.missingDate"
          type="date"
          placeholder="选择失踪日期"
        />
      </el-form-item>

      <el-form-item label="失踪地点" prop="missingLocation">
        <el-input v-model="formData.missingLocation" placeholder="请输入失踪地点" />
      </el-form-item>

      <el-form-item label="身高(cm)" prop="height">
        <el-input-number v-model="formData.height" :min="50" :max="250" />
      </el-form-item>

<!--      <el-form-item label="联系方式" prop="contactInfo">-->
<!--        <el-input v-model="formData.contactInfo" placeholder="请输入您的联系方式" />-->
<!--      </el-form-item>-->

      <!-- 添加图片上传 -->
      <el-form-item label="相关图片" prop="images">
        <el-upload
          v-model:file-list="fileList"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleImageChange"
          :on-remove="handleImageRemove"
          :limit="1"
        >
          <el-icon v-if="fileList.length === 0"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">{{ mode === 'post' ? '发布' : '提交' }}</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {postNoteAPI, updateNoteAPI} from "@/apis/notes";
import {useUserStore} from "@/stores/user";

const mode = defineModel('mode', {
  type: String,
  default: 'post'
})

const initialData = defineModel('initialData', {
  type: Object,
  default: () => ({
    title:'',
    describe:'',
    seekerName:'',
    age:0,
    sex:'male',
    missingDate:'',
    missingAddress:'',
    height:'',
    status:0,
    createdDate:'',
    imgUrl:''
  })
})

const emit = defineEmits(['submit-success'])

const formRef = ref(null)

const formData = ref({
  type: 'finding',
  title: initialData.value.title,
  description: initialData.value.describe,
  personName: initialData.value.seekerName,
  age: initialData.value.age,
  gender: initialData.value.sex,
  missingDate: initialData.value.missingDate,
  missingLocation: initialData.value.missingAddress,
  height: initialData.value.height,
  contactInfo: '',
  status: initialData.value.status,
  createdDate: initialData.value.createdDate,
  images: []
})

let tempFormData = initialData.value

const resetData=()=> {
  formData.value=tempFormData
  formData.value.description=tempFormData.describe
  formData.value.personName=tempFormData.seekerName
  formData.value.gender=tempFormData.sex
  formData.value.missingLocation =tempFormData.missingAddress
  formData.value.images=[]
}

defineExpose({
  resetData
})

const fileList = ref([
])

const rules = {
  type: [{ required: true, message: '请选择帖子类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  personName: [{ required: true, message: '请输入失踪人员姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  missingDate: [{ required: true, message: '请选择失踪日期', trigger: 'change' }],
  missingLocation: [{ required: true, message: '请输入失踪地点', trigger: 'blur' }],
  height: [{ required: true, message: '请输入身高', trigger: 'blur' }],
  contactInfo: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  images: [{ required: true, message: '请上传照片', trigger: 'change' }]
}

function handleImgUpload() {
  formData.images = []
  let imgUrl=initialData.value.imgUrl
  //提取路径
  const pathMatch = imgUrl.match(/\/\/[^\/]+\/(.*)/)
  if (pathMatch) {
    const path = pathMatch[1]
    downloadImage('/tianyan-bucket/'+path)
  }
  fileList.value = []
  fileList.value.push({
    name:'cover.png',
    url: initialData.value.imgUrl
  })
}

watch(() => mode.value, (newVal) => {
  if(mode.value === 'post'){
    formData.value = {}
    formData.value.gender = 'male'
    fileList.value = []
    return
  }
  handleImgUpload()

}, { immediate: true })

watch(() => initialData.value, (newVal) => {
  if (mode.value === 'edit' && newVal) {
    formData.value = {
      title: newVal.title,
      description: newVal.describe,
      personName: newVal.seekerName,
      age: newVal.age,
      gender: newVal.sex,
      missingDate: newVal.missingDate,
      missingLocation: newVal.missingAddress,
      height: newVal.height,
      status: newVal.status,
      createdDate: newVal.createdDate,
      images: []
    }
    handleImgUpload()
  }
}, { deep: true })

const submitForm = async () => {
  if(!useUserStore().getToken()){
    ElMessage.warning('请先登录')
    return
  }
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    const NOTE = {
      title: formData.value.title,
      describe: formData.value.description,
      seekerName: formData.value.personName,
      sex: formData.value.gender,
      age: formData.value.age,
      height: formData.value.height,
      missingAddress: formData.value.missingLocation,
      missingDate: formData.value.missingDate,
      createdDate:formData.value.createdDate?formData.value.createdDate:new Date().getTime(),
      updatedDate: new Date().getTime(),
      status:mode.value==='post'?0:initialData.value.status,
      uid:useUserStore().getUserInfo().uid
    }

    // 创建 FormData 对象
    const formDataObj = new FormData()
    // 检查并添加文件
    if (!formData.value.images || formData.value.images.length === 0) {
      ElMessage.warning('请上传图片')
      return
    }
    // 添加文件，确保文件存在
    formDataObj.set('file', formData.value.images[0])
    // 添加帖子数据
    formDataObj.set('notes', new Blob([JSON.stringify(NOTE)], {
      type: 'application/json'
    }))

    let res
    if (mode.value === 'post') {
      // 发帖模式
      res = await postNoteAPI(formDataObj)
    } else if(mode.value === 'edit'){
      // 更新模式
      formDataObj.set('notes',new Blob([JSON.stringify({
        ...NOTE,
        nid: initialData.value.nid
      })], {
        type: 'application/json'
      }))
      res = await updateNoteAPI(formDataObj)
    }
    if (res.code === '200') {
      ElMessage.success(mode.value === 'post' ? '发布成功' : '更新成功')
      emit('submit-success')
      resetForm()
    } else {
      ElMessage.error(res.msg || (mode.value === 'post' ? '发布失败' : '更新失败'))
    }
  } catch (error) {
    ElMessage.warning('请填写所有必填项')
  }
}

function downloadImage(imgUrl){
 fetch(imgUrl,{
    mode:'cors'
  }).then(res=>res.blob()).then(blob=>{
    // 将文件数据流保存到本地
   formData.value.images[0] = new File([blob], blob.size+'.'+blob.type.slice(6), {type: blob.type,encoding: 'utf-8'})
  }).catch(err => {
    console.error('图片下载失败',err)
  })
}

const resetForm = () => {
  if (formRef.value) {
    formData.value={}
    formData.value.gender='male'
    // 清空文件列表
    fileList.value = []
    // 清空formData中的images数组
    formData.images = []
  }
}
const handleImageChange = (uploadFile) => {
  if (fileList.value.length > 1) {
    fileList.value.shift()
  }
  // 确保存储原始文件对象
  formData.value.images = [uploadFile.raw]
}

const handleImageRemove = () => {
  formData.value.images = []
}
</script>

<style scoped>
.post-form-container {
  padding: 20px;
}

.post-form {
  max-width: 800px;
  margin: 0 auto;
}
</style>
